package com.cn.longdistancebusstation;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.annotation.LoginStatus;
import com.cn.longdistancebusstation.callback.OnCustomViewClickListener;
import com.cn.longdistancebusstation.fragment.IndexFragment;
import com.cn.longdistancebusstation.fragment.ScenicFragment;
import com.cn.longdistancebusstation.fragment.UserFragment;
import com.cn.longdistancebusstation.global.GlobalVariable;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.Integration;
import com.cn.longdistancebusstation.model.Result;
import com.cn.longdistancebusstation.model.Version;
import com.cn.longdistancebusstation.registerAndLogin.LoginActivity;
import com.cn.longdistancebusstation.util.PermissionUtils;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.support.v4.content.FileProvider.getUriForFile;

public class MainActivity extends FragmentActivity implements View.OnClickListener, OnCustomViewClickListener,ActivityCompat.OnRequestPermissionsResultCallback{
    private Fragment mHomeFragment;
    private UserFragment mPersonalFragment;
    private ScenicFragment mScenicFragment;
    private RelativeLayout layout_main_homepage,layout_main_myself,layout_main_scenic;
    private TextView text_main_menu,text_main_myself,text_main_scenic;
    private ImageView image_main_menu,image_main_myself,image_main_scenic;
    private long mExitTime;
    private AlertDialog.Builder mDialog;
    private int mCurIndex = 0;
    private ProgressBar mProgressBar;
    private Context mContext;
    private static final int MY_PERMISSION_REQUEST_CODE = 10000;
    private static final String TAG = MainActivity.class.getSimpleName();

    private String permissionInfo;
    private final int SDK_PERMISSION_REQUEST = 127;

    private String mCurrentVersionNumString;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        getPersimmions();
        updateVersion();

    }

    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.INTERNET);
            }
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.CAMERA);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
             */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取路径状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }
    @TargetApi(Build.VERSION_CODES.M)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }

        } else {
            return true;
        }
    }
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    private void initView() {
        layout_main_homepage = (RelativeLayout) findViewById(R.id.layout_main_homepage);
        layout_main_myself = (RelativeLayout) findViewById(R.id.layout_main_myself);
        layout_main_scenic=(RelativeLayout)findViewById(R.id.layout_main_scenic);

        text_main_menu = (TextView) findViewById(R.id.text_main_menu);
        text_main_myself = (TextView) findViewById(R.id.text_main_myself);
        text_main_scenic=(TextView)findViewById(R.id.text_main_scenic);

        image_main_menu = (ImageView) findViewById(R.id.image_main_menu);
        image_main_myself = (ImageView) findViewById(R.id.image_main_myself);
        image_main_scenic=(ImageView)findViewById(R.id.image_main_scenic);



        layout_main_homepage.setOnClickListener(this);
        layout_main_myself.setOnClickListener(this);
        layout_main_scenic.setOnClickListener(this);

        if (mHomeFragment == null) {
            mHomeFragment = new IndexFragment();
        }
        getSupportFragmentManager().beginTransaction().add(R.id.content_frame, mHomeFragment).commit();
    }

    @Override
    public void onClick(View v) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        switch (v.getId()) {
            case R.id.layout_main_homepage:
                if(mCurIndex == 0) return;
                if(mHomeFragment == null){
                    mHomeFragment = new IndexFragment();
                }
                else{
                    if(!mHomeFragment.isAdded()){
                        fragmentTransaction.add(R.id.content_frame, mHomeFragment);
                    }
                    if(mScenicFragment!=null){
                        fragmentTransaction.hide(mScenicFragment);
                    }
                    if(mPersonalFragment!=null){
                        fragmentTransaction.hide(mPersonalFragment);
                    }
                    fragmentTransaction.show(mHomeFragment).commit();
                }
                mCurIndex = 0;
                InitMenu();
                image_main_menu.setImageDrawable(getResources().getDrawable(R.mipmap.index_select));
                text_main_menu.setTextColor(getResources().getColor(R.color.themeColor));
                break;
            case R.id.layout_main_scenic:
                if(mCurIndex == 1) return;
                if(mScenicFragment == null){
                    mScenicFragment = new ScenicFragment();
                    mScenicFragment.setOnCustomViewClickListener(this);
                }
                if(!mScenicFragment.isAdded()) {
                    fragmentTransaction.add(R.id.content_frame, mScenicFragment);
                }
                if(mHomeFragment!=null){
                    fragmentTransaction.hide(mHomeFragment);
                }
                if(mPersonalFragment!=null){
                    fragmentTransaction.hide(mPersonalFragment);
                }
                fragmentTransaction.show(mScenicFragment).commit();
                mCurIndex = 1;
                InitMenu();
                image_main_scenic.setImageDrawable(getResources().getDrawable(R.mipmap.scenic_select));
                text_main_scenic.setTextColor(getResources().getColor(R.color.themeColor));
                break;
            case R.id.layout_main_myself:
                if(mCurIndex == 2) return;
                if(GlobalVariable.getLoginStatus() == LoginStatus.STATUS_LOGIN){
                    if(mPersonalFragment == null){
                        mPersonalFragment = new UserFragment();
                        mPersonalFragment.setOnCustomViewClickListener(this);
                    }
                    if(!mPersonalFragment.isAdded()){
                        fragmentTransaction.add(R.id.content_frame, mPersonalFragment);
                    }
                    if(mHomeFragment!=null){
                        fragmentTransaction.hide(mHomeFragment);
                    }
                    if(mScenicFragment!=null){
                        fragmentTransaction.hide(mScenicFragment);
                    }
                    fragmentTransaction.show(mPersonalFragment).commit();
                    mCurIndex = 2;
                    InitMenu();
                    image_main_myself.setImageDrawable(getResources().getDrawable(R.mipmap.us_select));
                    text_main_myself.setTextColor(getResources().getColor(R.color.themeColor));
                }
                else{
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    public void InitMenu(){
        image_main_menu.setImageDrawable(getResources().getDrawable(R.mipmap.index_normal));
        image_main_myself.setImageDrawable(getResources().getDrawable(R.mipmap.us_normal));
        image_main_scenic.setImageDrawable(getResources().getDrawable(R.mipmap.scenic_normal));

        text_main_myself.setTextColor(getResources().getColor(R.color.text_color));
        text_main_menu.setTextColor(getResources().getColor(R.color.text_color));
        text_main_scenic.setTextColor(getResources().getColor(R.color.text_color));
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if(mHomeFragment == null){
            mHomeFragment = new IndexFragment();
        }
        else{
            if(!mHomeFragment.isAdded()){
                fragmentTransaction.add(R.id.content_frame, mHomeFragment);
            }
            if(mPersonalFragment != null){
                fragmentTransaction.hide(mPersonalFragment);
            }
            if(mScenicFragment != null){
                fragmentTransaction.hide(mScenicFragment);
            }
            fragmentTransaction.show(mHomeFragment).commit();
        }
        mCurIndex = 0;
        InitMenu();
        image_main_menu.setImageDrawable(getResources().getDrawable(R.mipmap.index_select));
        text_main_menu.setTextColor(getResources().getColor(R.color.themeColor));
    }
    public void readExternalStorage(View view) {
        PermissionUtils.requestPermission(this, PermissionUtils.CODE_READ_EXTERNAL_STORAGE, mPermissionGrant);
    }

    public void writeExternalStorage(View view) {
        PermissionUtils.requestPermission(this, PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE, mPermissionGrant);
    }
    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
                    Toast.makeText(MainActivity.this, "Result Permission Grant CODE_READ_EXTERNAL_STORAGE", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE:
                    Toast.makeText(MainActivity.this, "Result Permission Grant CODE_WRITE_EXTERNAL_STORAGE", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    //更新版本
    private void updateVersion(){
        PackageManager packageManager = getPackageManager();
        try
        {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BuildConfig.SERVER_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            HttpService httpService = retrofit.create(HttpService.class);
            Call<Result<Version>> call = httpService.getVersionInfo(packageInfo.versionCode);
            call.enqueue(new Callback<Result<Version>>() {
                @Override
                public void onResponse(Call<Result<Version>> call, Response<Result<Version>> response) {
                    Result<Version> result = response.body();
                    if(result.getHead().getSuccess()){
                        //有新版本,弹出提示框询问是否更新
                        final Version version = result.getBody();
                        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
                        StringBuilder strHint = new StringBuilder("有新版本，是否更新?");
                        if(version.getRemark().length()>0){
                            strHint.append("本次更新内容如下:\n");
                            strHint.append(version.getRemark());
                        }
                        dialogBuilder.setMessage(strHint);
                        dialogBuilder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //开始下载
                                downloadFile(BuildConfig.SERVER_URL+version.getAPKPath());
                            }
                        });
                        dialogBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //取消，什么都不需要做
                            }
                        });
                        Dialog dialog = dialogBuilder.show();
                        dialog.setCanceledOnTouchOutside(false);
                    }
                    else{

                    }
                }

                @Override
                public void onFailure(Call<Result<Version>> call, Throwable t) {

                }
            });
        }
        catch(PackageManager.NameNotFoundException e)
        {}
    }
    private void downloadFile(final String fileURL){
        Log.d("路径",fileURL);
        //创建进度条
        final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
        View view = View.inflate(MainActivity.this, R.layout.download_file_progress, null);
        mProgressBar = (ProgressBar)view.findViewById(R.id.progressBar);
        mProgressBar.setMax(100);
        final TextView percentTextView = (TextView)view.findViewById(R.id.textView_hint);
        dialogBuilder.setView(view);
        final Dialog dialog = dialogBuilder.show();
        dialog.setCanceledOnTouchOutside(false);

        Thread thread = new Thread(new Runnable() {
            int writeDataSize = 0;
            @Override
            public void run() {
                try
                {
                    OkHttpClient httpClient = new OkHttpClient();
                    Request request =  new Request.Builder().url(fileURL).build();
                    okhttp3.Response response = httpClient.newCall(request).execute();
                    if(response.isSuccessful()){
                        final long fileSize = response.body().contentLength();
                        String savePath = Environment.getExternalStorageDirectory() + "/sdbusstation/";
                        Log.d("存储",savePath);
                        File file = new File(savePath+"sdbusstation.apk");
                        if(file.exists()){
                        }
                        else{
                            new File(savePath).mkdir();
                            file.createNewFile();
                        }
                        InputStream inputStream = response.body().byteStream();
                        FileOutputStream outputStream = new FileOutputStream(file);
                        byte[] bytes = new byte[10240];
                        int length;
                        while((length=inputStream.read(bytes)) != -1){
                            outputStream.write(bytes, 0, length);
                            outputStream.flush();
                            writeDataSize += length;
                            final long totalWriteSize = writeDataSize;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    int percent = (int) (totalWriteSize/(float)fileSize*100);
                                    mProgressBar.setProgress(percent);
                                    percentTextView.setText("正在下载:" + percent+"% / 100%");
                                }
                            });
                        }
                        dialog.dismiss();
                        installApk(file);
                    }
                }
                catch(IOException e)
                {
                    String strHint = e.getMessage();
                    Log.i("MainActivity", "");
                    dialog.dismiss();
                }
            }
        });
        thread.start();
        //
    }

    public static boolean isGrantExternalRW(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            activity.requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);
            return false;
        }
        return true;
    }


    private void installApk(File file) {
        if(!isGrantExternalRW(this)){
            return;
        }

        //调用系统安装程序
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
        // 第二个参数,即第一步中配置的authorities
            Uri contentUri = getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileProvider", file);
            // 声明需要的临时权限
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

}
